package cn.tedu.smartos.notice.service.impl;

import cn.tedu.smartos.activity.mapper.ActivityMapper;
import cn.tedu.smartos.activity.pojo.vo.ActivityVO;
import cn.tedu.smartos.baseuser.mapper.UserMapper;
import cn.tedu.smartos.notice.mapper.NoticeMapper;
import cn.tedu.smartos.notice.pojo.vo.ActivityNoticeVO;
import cn.tedu.smartos.notice.pojo.vo.SystemNoticeVO;
import cn.tedu.smartos.notice.service.NoticeService;
import cn.tedu.smartos.volunteer.mapper.VolunteerMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VolunteerMapper volunteerMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public List<SystemNoticeVO> getSystemNotices(Long userId) {
        // 获取用户所在区域
        List<Long> regionIds = noticeMapper.selectUserRegionIds(userId);

        // 查询系统公告
        return noticeMapper.selectSystemNotices(regionIds).stream()
                .map(notice -> {
                    SystemNoticeVO vo = new SystemNoticeVO();
                    vo.setNoticeId(notice.getNoticeId());
                    vo.setTitle(notice.getTitle());
                    vo.setContent(notice.getContent());
                    vo.setPublishTime(notice.getPublishTime());
                    vo.setIsRead(noticeMapper.isNoticeRead(userId, notice.getNoticeId()));
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<ActivityNoticeVO> getActivityNotices(Long userId) {
        // 获取志愿者ID
        Long volunteerId = volunteerMapper.selectByUserId(userId).getVolunteerId();

        // 查询志愿者的排班信息
        return noticeMapper.selectVolunteerSchedules(volunteerId).stream()
                .map(schedule -> {
                    ActivityNoticeVO vo = new ActivityNoticeVO();
                    vo.setScheduleId(schedule.getScheduleId());
                    vo.setActivityId(schedule.getActivityId());

                    // 获取活动信息
                    ActivityVO activity = activityMapper.selectActivityById(schedule.getActivityId());
                    vo.setActivityTitle(activity.getTitle());
                    vo.setLocation(activity.getLocation());

                    vo.setScheduleDate(schedule.getScheduleDate());
                    vo.setRemark(schedule.getRemark());
                    vo.setStatus(schedule.getStatus());
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public void markNoticeAsRead(Long userId, Long noticeId) {
        noticeMapper.insertMessageNotification(userId, noticeId);
    }
}